#import "GLPipes.h"

#import "pipes.c"

// defined by FreeSpace
float randBetween(float a, float b);

int NRAND_PIPES (int foo) {

    NSNumber *intValue = [NSNumber numberWithInt:(foo - 1)];

    float randValue = SSRandomFloatBetween(1.0, [intValue floatValue]);
    return [[NSNumber numberWithFloat:randValue] intValue];
}

@implementation GLPipes	

- (id)initWithFrame:(NSRect)frameRect
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    self = [super initWithFrame:frameRect];
    if (self) {
        _view = [[NSOpenGLView alloc] initWithFrame:frameRect];
        [self addSubview:_view];
    }
    
    [NSBundle loadNibNamed:@"GLPipes.nib" owner:self];
    factory = [defaults integerForKey:@"GLPipesDefine"];
    fisheye = [defaults integerForKey:@"GLPipesCloseUp"];
    tightturns = [defaults integerForKey:@"GLPipesTurns"];
    rotatepipes = [defaults integerForKey:@"GLPipesRotate"];


    [defineLevel setIntValue:factory];
    [closeUp setState:fisheye];
    [tightTurns setState:tightturns];
    [rotatePipes setState:rotatepipes];


    return self;
}

- (NSTimeInterval)animationTimeInterval
{
    return 0.01;
}

- (void)setFrameSize:(NSSize)newSize
{
    [super setFrameSize:newSize];
    [_view setFrameSize:newSize];
    _initedGL = NO;

}

- (void)drawRect:(NSRect)rects
{
    
    [_view lockFocus];
    
    if (!_initedGL) {
        init_pipes();
        reshape_pipes((int)rects.size.width, (int)rects.size.height);

        _initedGL = YES;
    }

    [_view unlockFocus];
}


- (void)oneStep
{
    if ([_view canDraw]) {
        [_view lockFocus];
        draw_pipes();
        [_view unlockFocus];
    }

    
    return;
}


- (BOOL)hasConfigureSheet { return YES; }
- (NSWindow*)configureSheet { return window; }

- (void)closeSheet:(id)sender
{
    [NSApp endSheet:window];
}

- (void)updateSelections:sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   	
    factory = [defineLevel intValue];
    fisheye = [closeUp state];
    tightturns = [tightTurns state];
    rotatepipes = [rotatePipes state];

    [defaults setInteger:factory forKey:@"GLPipesDefine"];
    [defaults setInteger:fisheye forKey:@"GLPipesCloseUp"];
    [defaults setInteger:tightturns forKey:@"GLPipesTurns"];
    [defaults setInteger:rotatepipes forKey:@"GLPipesRotate"];
}

@end